package exp7;


import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

// 鼠标按下和拖曳事件监听器
class MyMouserListener2 extends MouseAdapter {
    private int x1, y1; // 按下坐标
    private int x2, y2; // 拖曳坐标

    private Container canvas; // 画布区域

    public MyMouserListener2(Container canvas) {
        this.canvas = canvas;
    }

    // 按下
    public void mousePressed(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
    }

    // 拖曳
    public void mouseDragged(MouseEvent e) {
        Graphics g = canvas.getGraphics();
        // 清除画布区域
        g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        g.setColor(Color.RED);
        x2 = e.getX();
        y2 = e.getY();
        // 四种情况
        if (x2 > x1 && y2 > y1) {
            g.drawRect(x1, y1, x2 - x1, y2 - y1);
        } else if (x2 > x1 && y2 < y1) {
            g.drawRect(x1, y2, x2 - x1, y1 - y2);
        } else if (x2 < x1 && y2 > y1) {
            g.drawRect(x2, y1, x1 - x2, y2 - y1);
        } else if (x2 < x1 && y2 < y1) {
            g.drawRect(x2, y2, x1 - x2, y1 - y2);
        }

    }
}

public class Exp7_2 extends JFrame {
    void initUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setSize(700, 400);
        this.setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        Exp7_2 t = new Exp7_2();
        t.initUI();
        MyMouserListener2 listener = new MyMouserListener2(t);
        t.addMouseListener(listener);
        t.addMouseMotionListener(listener);
    }
}
